<template>
  <div class="profile-container">
    <div class="profile-card">
      <!-- 头部标题 -->
      <div class="profile-header">
        <h2><i class="el-icon-user-solid" /> 个人中心</h2>
        <div class="header-actions">
          <el-button
            type="text"
            icon="el-icon-refresh-right"
            @click="refreshData"
          >
            刷新
          </el-button>
        </div>
      </div>

      <!-- 主体内容 -->
      <div class="profile-content">
        <!-- 左侧信息卡片 -->
        <div class="info-card">
          <div class="avatar-wrapper">
            <el-avatar
              :size="120"
              :src="userInfo.avatar"
              class="avatar"
            />
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <div class="avatar-edit">
                <i class="el-icon-camera-solid" />
              </div>
            </el-upload>
          </div>

          <div class="user-meta">
            <h3 class="username">
              {{ userInfo.nickname }}
            </h3>
            <p class="position">
              {{ userInfo.department }}
            </p>
          </div>

          <el-divider><i class="el-icon-s-data" /> 账户信息</el-divider>

          <div class="info-list">
            <div class="info-item">
              <span class="info-icon"><i class="el-icon-user" /></span>
              <span class="info-label">登录名称</span>
              <span class="info-value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="info-icon"><i class="el-icon-mobile" /></span>
              <span class="info-label">手机号码</span>
              <span class="info-value">{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <span class="info-icon"><i class="el-icon-message" /></span>
              <span class="info-label">邮箱地址</span>
              <span class="info-value">{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="info-icon"><i class="el-icon-time" /></span>
              <span class="info-label">创建时间</span>
              <span class="info-value">{{ userInfo.createTime }}</span>
            </div>
          </div>
        </div>

        <!-- 右侧功能区域 -->
        <div class="function-card">
          <el-tabs
            v-model="activeTab"
            class="enhanced-tabs"
          >
            <el-tab-pane
              label="基本资料"
              name="info"
            >
              <div class="tab-content">
                <el-form label-position="top">
                  <el-form-item label="昵称">
                    <el-input
                      v-model="userInfo.nickname"
                      placeholder="请输入昵称"
                      class="enhanced-input"
                    />
                  </el-form-item>

                  <el-form-item label="性别">
                    <el-radio-group
                      v-model="userInfo.gender"
                      class="gender-selector"
                    >
                      <el-radio
                        :label="1"
                        border
                        size="medium"
                        class="gender-option"
                      >
                        <i class="el-icon-male" />
                        <span>男</span>
                      </el-radio>
                      <el-radio
                        :label="2"
                        border
                        size="medium"
                        class="gender-option"
                      >
                        <i class="el-icon-female" />
                        <span>女</span>
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="个人简介">
                    <el-input
                      v-model="userInfo.bio"
                      type="textarea"
                      :rows="4"
                      placeholder="介绍一下自己吧~"
                      maxlength="120"
                      show-word-limit
                      resize="none"
                      class="bio-textarea"
                    />
                  </el-form-item>

                  <el-button
                    type="primary"
                    class="save-btn"
                    @click="saveBasicInfo"
                  >
                    <i class="el-icon-check" /> 保存修改
                  </el-button>
                </el-form>
              </div>
            </el-tab-pane>

            <el-tab-pane
              label="修改密码"
              name="password"
            >
              <div class="tab-content">
                <el-form
                  ref="passwordForm"
                  :model="passwordForm"
                  :rules="passwordRules"
                  label-position="top"
                >
                  <el-form-item
                    label="旧密码"
                    prop="oldPassword"
                  >
                    <el-input
                      v-model="passwordForm.oldPassword"
                      type="password"
                      placeholder="请输入当前密码"
                      show-password
                      class="enhanced-input"
                    />
                  </el-form-item>

                  <el-form-item
                    label="新密码"
                    prop="newPassword"
                  >
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      placeholder="6-20位字母、数字或符号"
                      show-password
                      class="enhanced-input"
                    />
                    <div class="password-tips">
                      <span
                        v-if="passwordForm.newPassword.length > 0 && passwordForm.newPassword.length < 6"
                        class="weak"
                      >密码强度：弱</span>
                      <span
                        v-if="passwordForm.newPassword.length >= 6"
                        class="medium"
                      >密码强度：中</span>
                      <span
                        v-if="passwordForm.newPassword.length >= 10"
                        class="strong"
                      >密码强度：强</span>
                    </div>
                  </el-form-item>

                  <el-form-item
                    label="确认密码"
                    prop="confirmPassword"
                  >
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      placeholder="请再次输入新密码"
                      show-password
                      class="enhanced-input"
                    />
                  </el-form-item>

                  <div class="form-actions">
                    <el-button
                      type="primary"
                      class="save-btn"
                      @click="submitPassword"
                    >
                      <i class="el-icon-check" /> 保存
                    </el-button>
                    <el-button
                      class="reset-btn"
                      @click="resetPasswordForm"
                    >
                      <i class="el-icon-refresh" /> 重置
                    </el-button>
                  </div>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'Profile',
  data () {
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'))
      } else {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      activeTab: 'info',
      userInfo: {
        username: 'admin',
        nickname: '管理员',
        phone: '15888888888',
        department: '研发部门/董事长',
        email: 'ry@163.com',
        createTime: '2025-05-26',
        // avatar: require('@/assets/img/z.jpg'), // 直接使用本地图片
        avatar: this.$store.state.user.avatar, // 直接使用 Vuex 中的头像
        gender: 1,
        bio: '系统管理员'
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    safeAvatar () {
      return this.userInfo.avatar || require('@/assets/img/z.jpg')
    }
  },
  methods: {
    // 头像上传处理（纯前端预览）
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }

      // 创建本地预览
      const reader = new FileReader()
      // reader.onload = (e) => {
      //   const imageData = e.target.result // 定义局部变量存储base64数据
      //   this.userInfo.avatar = imageData

      //   // 调用Vuex action更新头像并等待完成
      //   this.$store.dispatch('user/uploadAvatar', file)
      //     .then(() => {
      //       // 使用正确的变量名
      //       this.userInfo.avatar = imageData
      //       localStorage.setItem('user_avatar', imageData)
      //       this.$message.success('头像更新成功')
      //     })
      // }

      reader.onload = (e) => {
        const base64Data = e.target.result

        // 同步更新三个地方
        this.$store.commit('user/SET_AVATAR', base64Data)
        this.userInfo.avatar = base64Data // 关键！更新本地数据
        localStorage.setItem('user_avatar', base64Data)
        sessionStorage.setItem('avatar', base64Data) // 双重保险
        this.$message.success('头像更新成功')
      }
      reader.readAsDataURL(file)

      return false // 阻止默认上传
    },

    // 保存基本信息（本地存储）
    saveBasicInfo () {
      // 模拟保存延迟
      setTimeout(() => {
        this.$message.success('基本信息保存成功（演示效果）')
        // 可以添加本地存储
        localStorage.setItem('demo_profile', JSON.stringify(this.userInfo))
      }, 500)
    },

    // 修改密码（前端验证）
    submitPassword () {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          // 模拟密码修改延迟
          setTimeout(() => {
            this.$message.success('密码修改成功（演示效果）')
            this.resetPasswordForm()

            // 模拟登出提示
            setTimeout(() => {
              this.$message.info('演示效果：密码修改后需要重新登录')
            }, 1500)
          }, 500)
        }
      })
    },

    // 重置密码表单
    resetPasswordForm () {
      this.$refs.passwordForm.resetFields()
    },

    // 刷新数据（从本地存储恢复）
    refreshData () {
      const savedData = localStorage.getItem('demo_profile')
      if (savedData) {
        this.userInfo = JSON.parse(savedData)
      }
      this.$message.success('数据已刷新（演示效果）')
    }
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color"; // 添加这行

$primary-color: #409EFF;
$success-color: #67C23A;
$warning-color: #E6A23C;
$danger-color: #F56C6C;
$info-color: #909399;
$border-color: #EBEEF5;
$bg-color: #F5F7FA;
$card-shadow: 0 6px 18px 0 rgba(0, 0, 0, 0.06);

.profile-container {
  padding: 24px;
  background-color: $bg-color;
  min-height: calc(100vh - 60px);

  .profile-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: $card-shadow;
    overflow: hidden;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    }

    .profile-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      border-bottom: 1px solid $border-color;
      background: linear-gradient(90deg, rgba(64,158,255,0.1) 0%, rgba(255,255,255,1) 100%);

      h2 {
        margin: 0;
        font-size: 20px;
        color: #303133;
        font-weight: 500;
        display: flex;
        align-items: center;

        i {
          margin-right: 12px;
          color: $primary-color;
          font-size: 24px;
        }
      }
    }

    .profile-content {
      display: flex;
      padding: 0;

      .info-card {
        width: 320px;
        padding: 24px;
        border-right: 1px solid $border-color;
        background-color: rgba(245, 247, 250, 0.5);

        .avatar-wrapper {
          position: relative;
          width: 120px;
          margin: 0 auto 24px;
          transition: all 0.3s;

          .avatar {
            display: block;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            border: 4px solid #fff;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
          }

          .avatar-uploader {
            position: absolute;
            right: 0;
            bottom: 0;
            z-index: 1;

            .avatar-edit {
              display: flex;
              justify-content: center;
              align-items: center;
              width: 36px;
              height: 36px;
              background: $primary-color;
              border-radius: 50%;
              color: #fff;
              cursor: pointer;
              transition: all 0.3s;
              box-shadow: 0 2px 6px rgba(64, 158, 255, 0.4);

              i {
                font-size: 18px;
              }

              &:hover {
                background: color.adjust($primary-color, $lightness: -10%); // 推荐
              }
            }
          }

          &:hover {
            .avatar {
              transform: scale(1.05);
            }
          }
        }

        .user-meta {
          text-align: center;
          margin-bottom: 24px;

          .username {
            margin: 0 0 8px;
            font-size: 18px;
            color: #303133;
            font-weight: 500;
          }

          .position {
            margin: 0;
            font-size: 14px;
            color: $info-color;
          }
        }

        .el-divider {
          ::v-deep .el-divider__text {
            background-color: transparent;
            color: $info-color;
            font-size: 13px;
            padding: 0 12px;

            i {
              margin-right: 6px;
            }
          }
        }

        .info-list {
          margin-top: 20px;

          .info-item {
            display: flex;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px dashed $border-color;
            transition: all 0.3s;

            &:last-child {
              border-bottom: none;
            }

            &:hover {
              background-color: rgba($primary-color, 0.05);
              transform: translateX(4px);
            }

            .info-icon {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 32px;
              height: 32px;
              background-color: rgba($primary-color, 0.1);
              border-radius: 50%;
              margin-right: 12px;
              color: $primary-color;
            }

            .info-label {
              font-size: 13px;
              color: $info-color;
              width: 80px;
            }

            .info-value {
              flex: 1;
              font-size: 13px;
              color: #606266;
              text-align: right;
              word-break: break-all;
            }
          }
        }
      }

      .function-card {
        flex: 1;
        padding: 24px;

        .enhanced-tabs {
          ::v-deep {
            .el-tabs__header {
              margin: 0 0 24px;
            }

            .el-tabs__nav-wrap::after {
              height: 1px;
              background-color: $border-color;
            }

            .el-tabs__item {
              font-size: 15px;
              padding: 0 20px;
              height: 50px;
              font-weight: 500;

              &:hover {
                color: $primary-color;
              }
            }

            .el-tabs__active-bar {
              height: 3px;
              border-radius: 3px 3px 0 0;
            }
          }
        }

        .tab-content {
          padding: 0 16px;

          .el-form {
            max-width: 600px;
          }

          .enhanced-input {
            ::v-deep .el-input__inner {
              height: 42px;
              border-radius: 8px;
              transition: all 0.3s;

              &:focus {
                border-color: $primary-color;
                box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
              }
            }
          }

        .gender-selector {
        display: flex;
        gap: 12px;
        margin-top: 8px;

        ::v-deep .el-radio-button {
        margin-right: 0;
        flex: 1;

        .el-radio-button__inner {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 10px 20px;
        border-radius: 8px;
        transition: all 0.3s;

        i {
            font-size: 16px;
            margin-right: 6px;
        }
        }

        &.is-active {
        .el-radio-button__inner {
            background-color: rgba($primary-color, 0.05);
            border-color: $primary-color;
            color: $primary-color;
            box-shadow: none;

            i {
            color: inherit;
            }
        }

        &:first-child .el-radio-button__inner i {
            color: $primary-color;
        }

        &:last-child .el-radio-button__inner i {
            color: $danger-color;
        }
        }

            &:hover:not(.is-active) {
                .el-radio-button__inner {
                    border-color: $primary-color;
                }
            }
          }
        }

          .bio-textarea {
            ::v-deep .el-textarea__inner {
              border-radius: 8px;
              transition: all 0.3s;
              padding: 12px;

              &:focus {
                border-color: $primary-color;
                box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
              }
            }
          }

          .password-tips {
            margin-top: 8px;
            font-size: 12px;

            .weak {
              color: $danger-color;
            }
            .medium {
              color: $warning-color;
            }
            .strong {
              color: $success-color;
            }
          }

          .form-actions {
            margin-top: 32px;
            display: flex;
            justify-content: flex-start;
          }

          .save-btn {
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s;
            box-shadow: 0 4px 12px rgba($primary-color, 0.2);

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 6px 16px rgba($primary-color, 0.3);
            }

            i {
              margin-right: 6px;
            }
          }

          .reset-btn {
            padding: 12px 24px;
            border-radius: 8px;
            margin-left: 16px;
            transition: all 0.3s;

            &:hover {
              color: $primary-color;
              border-color: $primary-color;
              background-color: rgba($primary-color, 0.05);
            }
          }
        }
      }
    }
  }
}
</style>
